package com.lagou.mapper;

import com.lagou.config.AnnoMapperBuilder;
import com.lagou.config.BeanDefinition;
import com.lagou.config.DependInfo;
import com.lagou.factory.FactoryBean;
import com.lagou.pojo.Configuration;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;

/**
 * @author: wudong
 * @create: 2021-05-31 13:56
 **/
public class AnnoMapperConfig implements MapperConfig {

    private String basePackage;

    private DataSource dataSource;

    public AnnoMapperConfig(String basePackage, DataSource dataSource) {
        this.basePackage = basePackage;
        this.dataSource = dataSource;
    }

    @Override
    public void postProcessAfterBeanDefiInit(Consumer<BeanDefinition> registry) {
        Configuration configuration = new Configuration();
        configuration.setDataSource(dataSource);
        AnnoMapperBuilder annoMapperBuilder = new AnnoMapperBuilder(configuration);
        try {
            annoMapperBuilder.parse(basePackage);

            SpringSqlSessionFactory springSqlSessionFactory = new SpringSqlSessionFactory(configuration);
            SpringSqlSession springSqlSession = new SpringSqlSession(springSqlSessionFactory);

            Set<Class<?>> allMapper = configuration.getAllMapper();
            for (Class<?> aClass : allMapper) {
                Object mapper = springSqlSession.getMapper(aClass);
                BeanDefinition beanDefinition = new BeanDefinition(){

                    @Override
                    public Class<?> getBeanClass() {
                        return mapper.getClass();
                    }

                    @Override
                    public List<String> getBeanNames() {
                        return new ArrayList<>();
                    }

                    @Override
                    public List<DependInfo> getDependsOn() {
                        return new ArrayList<>();
                    }

                    @Override
                    public FactoryBean getFactoryBean() {
                        return new FactoryBean() {
                            @Override
                            public Object getObject() {
                                return mapper;
                            }

                            @Override
                            public Class<?> getObjectType() {
                                return mapper.getClass();
                            }
                        };
                    }
                };
                registry.accept(beanDefinition);

            }
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
}
